/*	$Id: pbuf.c 6 2008-07-29 02:30:10Z phrakt $	*/
/*
 * Copyright (c) 2003, 2005 Jean-Francois Brousseau <jfb@openbsd.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 */

#include <sys/types.h>

#include <stdlib.h>
#include <unistd.h>

#include "pbuf.h"
#include "queue.h"
#include "mpool.h"
#include "pforge.h"


static PF_MPOOL *pf_pbuf_pool;
static PF_MPOOL *pf_pbuf_clspool;



/*
 * pf_pbuf_init()
 *
 */
int
pf_pbuf_init(void)
{
	pf_pbuf_pool = pf_mpool_alloc(PFPBUF_SIZE, 1000, 0);
	if (pf_pbuf_pool == NULL) {
		return (-1);
	}

	pf_pbuf_clspool = pf_mpool_alloc(PFPBUF_CLSIZE, 128, 0);
	if (pf_pbuf_pool == NULL) {
		return (-1);
	}

	return (0);
}


/*
 * pf_pbuf_cleanup()
 *
 */
void
pf_pbuf_cleanup()
{
	if (pf_pbuf_pool != NULL) {
		pf_mpool_destroy(pf_pbuf_pool);
		pf_pbuf_pool = NULL;
	}
}


/*
 * pf_pbuf_alloc()
 *
 * Allocate a buffer from the pool.
 * Returns a pointer to the allocated buffer on success, or NULL on failure.
 */
PF_PBUF*
pf_pbuf_alloc(int flags)
{
	void *buf;
	struct pf_pbuf_hdr *hdr;

	buf = pf_mpool_get(pf_pbuf_pool, MPALLOC_WAIT);
	if (buf != NULL) {
		hdr = (struct pf_pbuf_hdr *)buf;
		hdr->pb_flags = 0;
		hdr->pb_len = 0;
		hdr->pb_start = NULL;
	}

	return (buf);
}
